<?php

namespace App\Http\Middleware;

use Closure;
use App\Common\ApiResponse;

class VerifySignature
{
    use ApiResponse;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $timestamp = $request->timestamp ?? $request->header('timestamp');
        $signature = $request->signature ?? $request->header('signature');

        // 签名参数
        if (!$timestamp || !$signature) {
            return $this->failed('缺少签名参数');
        }

        // 接口超时
        if (app()->environment() == 'production') {
            if (now()->getTimestamp()-$timestamp > config('app.api_timeout')) {
                return $this->failed('接口已过期');
            }
        }

        $sign = sha1(base64_encode('timestamp=' . $timestamp . config('app.secret')));

        if ($sign != $signature) {
            return $this->failed('接口验签失败');
        }

        return $next($request);
    }
}